package main

import (
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"time"

	"github.com/spf13/cobra"
)

var (
	keepalive = false
	clientCmd = &cobra.Command{
		Use: "client",
		Run: runClient,
	}
)

func init() {
	clientCmd.Flags().BoolVarP(&keepalive, "keepalive", "k", keepalive, "")
	rootCmd.AddCommand(clientCmd)
}

func runClient(cmd *cobra.Command, args []string) {
	clt := &http.Client{
		Transport: &http.Transport{
			Proxy: http.ProxyFromEnvironment,
			Dial: func(network, address string) (net.Conn, error) {
				dial := &net.Dialer{
					Timeout:   30 * time.Second,
					KeepAlive: 30 * time.Second,
				}
				c, err := dial.Dial(network, address)
				if err != nil {
					return nil, err
				}
				fmt.Println("Connect:", c.LocalAddr().String())
				return c, nil
			},
			MaxIdleConns:          1000,
			MaxIdleConnsPerHost:   1000, // NOTE:!!!
			TLSHandshakeTimeout:   10 * time.Second,
			ExpectContinueTimeout: 4 * time.Second,
			ResponseHeaderTimeout: 3 * time.Second,
		},
		Timeout: 30 * time.Second,
	}

	if !keepalive {
		transport := clt.Transport.(*http.Transport)
		transport.DisableKeepAlives = true
	}

	for i := 0; i < 10; i++ {
		go func() {
			for {
				resp, err := clt.Get("http://" + addr + "/aa")
				if err != nil {
					panic(err)
				}
				_, err = ioutil.ReadAll(resp.Body)
				if err != nil {
					panic(err)
				}
				err = resp.Body.Close()
				if err != nil {
					panic(err)
				}
				time.Sleep(time.Second)
			}
		}()
	}

	select {}
}
